package com.cskaoyan.work2.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;
    static {
        // SQL会话的工厂 → 生产SqlSession → Connection的封装
        // SqlSession是Connection的封装，Connection线程 不安全 → SqlSession线程不安全
        // SqlSessionFactory → 线程安全，可以全局共享
        //InputStream inputStream = MyBatisUtil.class.getClassLoader().getResourceAsStream("mybatis.xml");
        // MyBatis也提供了一个方法也可以获取类加载路径下的资源为一个字节输入流
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    }
    public static SqlSession getSqlSession() {
        // openSession()不会自动提交事务，需要手动提交
        return sqlSessionFactory.openSession(); // Connection
    }

    public static SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);//是否自动提交
    }
}
